import {
  Controller,
  Get,
  Post,
  Body,
  Delete,
  Param,
  ParseIntPipe,
  Patch,
  UseGuards,
  UseInterceptors,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { ObjectType, CommonResponse } from 'src/types/index';
import { UsersService } from '../services/users.service';
import { responseWrapper } from 'src/utils';
import { AuthGuard } from 'src/guard/auth.guard';
import { LoggingInterceptor } from 'src/interceptors/logging.interceptor';
import { CreateUserTdo } from '../dto/create.user.dto';

@Controller('users')
@UseGuards(AuthGuard) // 2、在控制器中使用守卫
// @UseInterceptors(LoggingInterceptor) // 控制器中使用拦截器
export class UsersController {
  constructor(private readonly userService: UsersService) {}

  // 使用校验
  @Post()
  async createUser(@Body() data: CreateUserTdo): Promise<CommonResponse> {
    try {
      const res = await this.userService.createUser(data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Delete(':id')
  // @UseGuards(AuthGuard) // 3、接口层面使用
  @UseInterceptors(LoggingInterceptor) // 接口中使用拦截器
  async deleteUserById(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      const res = await this.userService.deleteUserById(id);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Patch(':id')
  async modifyUserById(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() data: ObjectType,
  ): Promise<CommonResponse> {
    try {
      const res = await this.userService.modifyUserById(id, data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get()
  async userList(): Promise<CommonResponse> {
    console.log('获取用户数据');
    // 抛出的异常会被 异常过滤器捕获处理
    // throw new HttpException('获取数据错误', HttpStatus.OK);
    try {
      const res = await this.userService.userList();
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get(':id')
  async getUserById(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      const res = await this.userService.userById(id);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Post('/login')
  async login(@Body() data: ObjectType) {
    try {
      return this.userService.login(data);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }
}
